#include "EdgeWatcher.h"


EdgeWatcher::EdgeWatcher()
{
	state = 255;
	sampleClock = Counter<unsigned char>(0,0);
}

EdgeWatcher::EdgeWatcher(BitPointer b, unsigned char rate)
{
	state = 255;
	bit = b;
	sampleClock = Counter<unsigned char>(0, rate);
}

void EdgeWatcher::sampleSignal()
{
	//first set the previous state
	unsigned char prev = state;
	//do first check to determine if this is high or low
	state = bit.getBit();

	//do the first transition check
	if(prev == 255 && state == EdgeWatcher::LowEdge)
		state = EdgeWatcher::FallingEdge;
	else if(prev == 255 && state == EdgeWatcher::HighEdge)
		state = EdgeWatcher::RisingEdge;
	if(prev == 255) //if previous was undefined previously no need to continue.
		return;
	//set convert prev to only high or low.
	prev = prev & 0x01;
	//check for rising and falling event
	//prev & state == 0 used to determin if event happened.
	if(prev & state == 0 && state == EdgeWatcher::HighEdge)//rising event 
		state = EdgeWatcher::RisingEdge;
	else if(prev & state == 0 && state == EdgeWatcher::LowEdge) //falling event
		state = EdgeWatcher::FallingEdge;

	return;
}


void EdgeWatcher::run()
{
	if(sampleClock.flag()==1) //take a sample
	{
		this->sampleSignal();
		sampleClock.resetCount(0);
	}
	//increment the time now
	sampleClock++;
}


unsigned char EdgeWatcher::rising()
{
	if(state == EdgeWatcher::RisingEdge)
		return true;
	else
		return false;
}

unsigned char EdgeWatcher::falling()
{
	if(state == EdgeWatcher::FallingEdge)
		return true;
	else
		return false;
}

unsigned char EdgeWatcher::high()
{
	if(state == EdgeWatcher::RisingEdge || state == EdgeWatcher::HighEdge)
		return true;
	else
		return false;
}

unsigned char EdgeWatcher::low()
{
	if(state == EdgeWatcher::FallingEdge || state == EdgeWatcher::LowEdge)
		return true;
	else
		return false;
}



